//
//  VideoPlayerViewController.m
//  VideoAndListen
//
//  Created by 我爱的妞 on 15/10/20.
//  Copyright © 2015年 @@叶一闽. All rights reserved.
//

#import "VideoPlayerViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "MBProgressHUD+show.h"

@interface VideoPlayerViewController ()

@property (nonatomic, retain) MPMoviePlayerViewController *playerVC;
@property (nonatomic, retain) MPMoviePlayerController *playerController;
@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) UIButton *selectButton;
@property (nonatomic, retain) UIView *selectView;
@property (nonatomic, retain) UIView *topView;
@property (nonatomic, retain) UIView *bottomView;
@property (nonatomic, retain) UIView *tapView;
@property (nonatomic, assign) BOOL isPlaying;
@property (nonatomic, retain) UISlider *slider;
@property (nonatomic, retain) UILabel *timeLabel;
@property (nonatomic, retain) UIButton *playButton;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, assign) NSInteger hidden;
@property (nonatomic, assign) BOOL isFirst;
@property (nonatomic, retain) UISlider *bgSlider;
@property (nonatomic, assign) BOOL isTouch;

@end

@implementation VideoPlayerViewController


- (void)dealloc{
    
    [_playerController release];
    [_playerVC release];
    [_timer invalidate];
    
    [super dealloc];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    self.playerVC.view.frame = CGRectMake(0, 0, 667 * SCALEH, 375 * SCALEW);
    
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [UIViewController attemptRotationToDeviceOrientation];
    [self createMediaPlayer];
}

- (void)createMediaPlayer{
    
    self.isTouch = NO;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    UISwipeGestureRecognizer *swp1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(forward:)];
    swp1.direction = UISwipeGestureRecognizerDirectionRight;
    UISwipeGestureRecognizer *swp2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(backward:)];
    swp2.direction = UISwipeGestureRecognizerDirectionLeft;
    
    self.playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:self.url]];
    self.playerController.movieSourceType = MPMovieSourceTypeFile;
    self.playerController = self.playerVC.moviePlayer;
//    self.playerController.scalingMode = MPMovieScalingModeFill;
    self.playerController.controlStyle = MPMovieControlStyleNone;
    
    [self.view addSubview:self.playerVC.view];
    [self addChildViewController:self.playerVC];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(valueChange) name:MPMovieDurationAvailableNotification object:nil];
    [self.playerController prepareToPlay];
    
    self.tapView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 667 * SCALEH, 375 * SCALEW)];
    self.tapView.alpha = 1;
    [self.tapView addGestureRecognizer:tap];
    [self.tapView addGestureRecognizer:swp1];
    [self.tapView addGestureRecognizer:swp2];
    
    [self.playerVC.view addSubview:self.tapView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sizeChange) name:MPMovieNaturalSizeAvailableNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stateChange) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
    
    [self createSubViews];
    
    [_playerVC release];
    [tap release];
    [swp1 release];
    [swp2 release];
    [_tapView release];
}

- (void)createSubViews{
    
    self.isPlaying = YES;
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 667 * SCALEH, 40)];
    self.topView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.8];
    self.topView.alpha = 0.8;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0 * SCALEW, 0 * SCALEH, 40 * SCALEW, 40 * SCALEW);
    [backBtn setImage:[UIImage imageNamed:@"btn_nav_back@2x"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.topView addSubview:backBtn];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(60 * SCALEH, 7 * SCALEW, (667 - 80) * SCALEH, 30 * SCALEW)];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.text = self.currentTitle;
    [self.topView addSubview:self.titleLabel];
    
    [self.playerVC.view addSubview:self.topView];
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, (375 - 60) * SCALEW, 667 * SCALEH, 60 * SCALEW)];
    self.bottomView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.8];
    self.bottomView.alpha = 0.8;
    
    [self.playerVC.view addSubview:self.bottomView];
    
    self.bgSlider = [[UISlider alloc] initWithFrame:CGRectMake(152, 20 * SCALEW, (HEIGHT - 152), 20 * SCALEW)];
//    self.bgSlider.minimumValue = 1;
    self.bgSlider.thumbTintColor = [UIColor clearColor];
    self.bgSlider.minimumTrackTintColor = [UIColor grayColor];
    self.bgSlider.maximumTrackTintColor = [UIColor clearColor];
    self.bgSlider.userInteractionEnabled = NO;
    
    [self.bottomView addSubview:self.bgSlider];
    
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(152, 20 * SCALEW, (HEIGHT - 164), 20 * SCALEW)];
    self.slider.maximumTrackTintColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.2];
    self.slider.userInteractionEnabled = NO;
    
//    self.slider.minimumValue = 1;
    
    [self.slider addTarget:self action:@selector(sliderChangeValue:) forControlEvents:UIControlEventTouchUpInside];
    [self.slider addTarget:self action:@selector(sliderTouchAction) forControlEvents:UIControlEventTouchDown];
    [self.slider addTarget:self action:@selector(sliderValueChange) forControlEvents:UIControlEventValueChanged];
    
    [self.bottomView addSubview:self.slider];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(40 * SCALEH, 20 * SCALEW, 110, 20 * SCALEW)];
    self.timeLabel.font = [UIFont systemFontOfSize:11.f];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.text = @"00:00:00/00:00:00";
    
    [self.bottomView addSubview:self.timeLabel];
    
    //播放暂停按钮
    UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    playBtn.frame = CGRectMake(7 * SCALEH, 15 * SCALEW, 32 * SCALEW, 32 * SCALEW);
    [playBtn setBackgroundImage:[UIImage imageNamed:@"pause@2x"] forState:UIControlStateNormal];
    [playBtn addTarget:self action:@selector(tapTwoAction) forControlEvents:UIControlEventTouchUpInside];
    self.playButton = playBtn;
    
    [self.bottomView addSubview:playBtn];
    
    [_topView release];
    [_timeLabel release];
    [_bottomView release];
    [_bgSlider release];
    [_slider release];
    [_timeLabel release];
}

// ***********slider事件

//点击slider让计时器停止
- (void)sliderTouchAction{
    self.isTouch = YES;
}

//slider事件
- (void)sliderChangeValue:(UISlider *)slider{
    
    [self.playerController setCurrentPlaybackTime:slider.value];
}

//slider拖动过程中
- (void)sliderValueChange{
    
    [self floatChangeTime:self.slider.value];
}

// ****************


//获取屏幕尺寸
- (void)sizeChange{
    [self setPlayerTime];
}

//通知中心状态改变时
- (void)stateChange{
    if (self.playerController.playbackState == MPMoviePlaybackStatePlaying) {
        self.isTouch = NO;
    }
}

//获取电影时长事件
- (void)valueChange{
    
    self.slider.userInteractionEnabled = YES;
    self.slider.maximumValue = self.playerController.duration;
    self.bgSlider.maximumValue = self.playerController.duration;
    
    NSLog(@"%f--%f", self.slider.maximumValue, self.playerController.duration);
    /*
    NSInteger hour = self.slider.maximumValue / 3600;
    NSInteger min = (self.slider.maximumValue - 3600 * hour) / 60;
    NSInteger second = self.slider.maximumValue - 3600 * hour - min * 60;
    self.timeLabel.text = [NSString stringWithFormat:@"00:00:00/%.2ld:%.2ld:%.2ld", hour, min, second];
     */
    [self floatChangeTime:self.slider.value];
    [self timerStart];
}

//计时器事件
- (void)timeLabelText:(NSTimer *)object{
    
    NSLog(@"%f--%f--%f", self.playerController.playableDuration, self.bgSlider.maximumValue, self.slider.maximumValue);
    
    self.bgSlider.value = self.playerController.playableDuration;
    
    if (self.isTouch == NO) {
        self.slider.value = self.playerController.currentPlaybackTime;
        CGFloat max = self.slider.maximumValue - self.slider.value;
        [self hiddenAllView];
        [self floatChangeTime:max];
    }
}

//记录隐藏时间
- (void)hiddenAllView{
    
    if (self.topView.alpha > 0.6) {
        self.hidden++;
        NSLog(@"%ld", self.hidden);
        if (self.hidden == 6) {
            [UIView animateWithDuration:0.8 animations:^{
                self.topView.alpha = 0;
                self.bottomView.alpha = 0;
            }];
            self.hidden = 0;
        }
    }
}

//浮点转时间
- (void)floatChangeTime:(CGFloat)f{
    
    NSInteger hour = self.slider.maximumValue / 3600;
    NSInteger min = (self.slider.maximumValue - 3600 * hour) / 60;
    NSInteger second = self.slider.maximumValue - 3600 * hour - min * 60;
    
    NSInteger hour1 = self.slider.value / 3600;
    NSInteger min1 = ((NSInteger)self.slider.value % 3600) / 60;
    NSInteger second1 = (NSInteger)self.slider.value % 60;
    
    self.timeLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld/%.2ld:%.2ld:%.2ld", hour1, min1, second1, hour, min, second];
}

//返回事件
- (void)backAction:(UIButton *)item{
    
    [self timerPause];
    
    [self.playerController stop];
    
    [self.delegate timeFromVideo:self.slider.value];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//轻点屏幕事件
- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    if (self.topView.alpha > 0 && tap.state == UIGestureRecognizerStateEnded) {
        
        [UIView animateWithDuration:0.8 animations:^{
            self.topView.alpha = 0;
            self.bottomView.alpha = 0;
            self.hidden = 0;
        }];
        
    }else if (self.topView.alpha == 0 && tap.state == UIGestureRecognizerStateEnded){
        [UIView animateWithDuration:0.8 animations:^{
            self.topView.alpha = 0.8;
            self.bottomView.alpha = 0.8;
        }];
    }
    
}

//play/pause事件
- (void)tapTwoAction{
    
    if (self.isPlaying == YES) {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"play@2x"] forState:UIControlStateNormal];
        [self.playerController pause];
    }else{
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"pause@2x"] forState:UIControlStateNormal];
        [self.playerController play];
    }
    
    self.isPlaying = !self.isPlaying;
}

//设置初始时间
- (void)setPlayerTime{
    
    if (self.playerTime > 300) {
        
        NSInteger hour1 = self.playerTime / 3600;
        NSInteger min1 = self.playerTime / 60;
        NSInteger second1 = (NSInteger)self.playerTime % 60;
        NSString *str = [NSString stringWithFormat:@"上回看到了%.2ld:%.2ld:%.2ld", hour1, min1, second1];
        [MBProgressHUD showVerInfoWithText:str andView:self.tapView];
        
        self.slider.value = self.playerTime;
        [self.playerController setCurrentPlaybackTime:self.playerTime];
    }

}

//计时器停止
- (void)timerPause{
    [self.timer invalidate];
//    NSLog(@"%ld", self.timer.retainCount);
    self.timer = nil;
}

//计时器开始
- (void)timerStart{
    self.timer = nil;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timeLabelText:) userInfo:nil repeats:YES];
}

//快进
- (void)forward:(UISwipeGestureRecognizer *)swip{
    
    if (swip.state == UIGestureRecognizerStateEnded && self.playerController.playbackState == MPMoviePlaybackStatePlaying) {
        self.isTouch = YES;
        
        CGFloat f = self.slider.value + 8 + self.playerController.duration * 0.015;
        
        if (f > self.playerController.duration - 1) {
            f = self.slider.value;
        }
        
        self.slider.value = f;
        self.playerController.currentPlaybackTime = self.slider.value;
    }
    
}

//回退
- (void)backward:(UISwipeGestureRecognizer *)swip{
    
    if(swip.state == UIGestureRecognizerStateEnded && self.playerController.playbackState == MPMoviePlaybackStatePlaying) {
        self.isTouch = YES;
        CGFloat b = self.slider.value - 8 - self.playerController.duration * 0.015;
        if (b < 0) {
            b = 0;
        }
        self.slider.value = b;
        self.playerController.currentPlaybackTime = self.slider.value;
    }
    
}


// ********强制横屏
- (BOOL)shouldAutorotate
{
//    self.playerVC.view.frame = CGRectMake(0, 0, 667 * SCALEH, 375 * SCALEW);
    return NO;
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeRight;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeRight;
}



@end
